*===============================================================================
* Project title		Savings Accounts to Borrow Less	
* PIs			Felipe Kast, Dina Pomeranz 
* File name		2e_tables_analysis_robustness.do
*-------------------------------------------------------------------------------
* Description		Creates robustness check tables 
* Outputs		Tables 8, A21, A22
* Spaces per tab 	8 
*===============================================================================

*===============================================================================
*TOC
*1)	Prepare data for analysis
*2)	Tables
*2.1)	Differential effect by account type
*2.2)	Lee bounds table
*2.3)	Inverse probability table
*===============================================================================

*===============================================================================
* Section 1 - Prepare data for analysis
*===============================================================================

clear all
global path "~/file_server/project_savings/2_shared/impact/do/November2019"	// Path to processed data
global results "$path/results"		
cd "$results"									// Change to directory to store results
set more off

*Loading processed data
	use $path/datasets/impactDatabase.dta, clear

*===============================================================================
* Section 2 - Tables 
*===============================================================================
* Section 2.1 - Table on differential effect by account type
*-------------------------------------------------------------------------------
*2.1.1 - Table code
	eststo clear
	foreach y in w5_shortTermBorrowing stBorrowTotalIndex anxietyFuture 	///
		economicDifficulty  { 
	
		reg d.`y' // Mark subjects nonmissing in both periods
		egen t1 = max(e(sample)), by(idBaseSurvey)
		
		reghdfe `y' c.accountAccess#c.post c.peerGroupTreatment#c.post 	/// Regressing relevant outcomes on treatment x post 
		post if t1 == 1, abs(idBaseSurvey) 				///
		vce(cluster groupId) 
		
		distinct idBaseSurvey  if e(sample) 
		estadd scalar num_ind = r(ndistinct)
		estadd local ind_fixeff = "Yes"
		estadd local stratum_post_fe = "Yes"
		
		// adding control mean 
		sum `y' if accountAccess == 0 & post == 1
		if (abs(`r(mean)') < 100) {
			estadd local control_mean = trim("`: display %12.3fc r(mean)'")
		} 
		else {
			estadd local control_mean = trim("`: display %12.0fc r(mean)'")
		}

		drop t1	
		eststo
		local i = `i' + 1 //updates counter	
	}
	
// numberConsumptionCutbacks is outside loop because it's only for economicShock2009 == 1

	reg d.numberConsumptionCutbacks 
	egen t1 = max(e(sample)), by(idBaseSurvey)	
	
	reghdfe numberConsumptionCutbacks c.accountAccess#c.post 		///
	c.peerGroupTreatment#c.post post if t1 == 1  & 				///
	economicShock2009 == 1, abs(idBaseSurvey) 				///
	vce(cluster groupId) 
	
        distinct idBaseSurvey  if e(sample) 
        estadd scalar num_ind = r(ndistinct)
        estadd local ind_fixeff = "Yes"
	
	// adding control mean 
	sum numberConsumptionCutbacks if accountAccess == 0 & post == 1
	if (abs(`r(mean)') < 100) {
		estadd local control_mean = trim("`: display %12.3fc r(mean)'")
	} 
	else {
		estadd local control_mean = trim("`: display %12.0fc r(mean)'")
	}

	drop t1	
	eststo
	
* 2.1.2 Writes table ---------------------------------------------------------	

	esttab est* using tab_effect_by_account_type.tex, replace					///
	cells(b(star fmt(%12.3fc)) se(par fmt(%12.3fc))) label style(tex) nonumber			///
	stats( control_mean num_ind N ind_fixeff, fmt(%12.3fc %12.0fc %12.0fc)				///
	label("Control mean" "\hline Individuals" "Observations"					///
	"Individual FE")) mlabels(,none) 								///	
	collabels(, none) eqlabels(, none)  								///
	keep(c.accountAccess#c.post c.peerGroupTreatment#c.post )					///
	varlabels(c.accountAccess#c.post "Account $\times$ post" 					///
	c.peerGroupTreatment#c.post "Additional peer group $\times$ post"  ) 				///
	starlevels(* 0.1 ** 0.05 *** 0.01) 								///
	prehead(\begin{tabular}{l*{@M}{c}} \hline \hline 						///
	&(1) & (2) & (3) & (4) & (5) \\ 								///
	& Short-term &Short-term & Anxiety & Recent &Consumption \\ 					///
	& borrowing & borrowing & about & economic & cutback  \\ 					///
	& amount & categories & financial & difficulty & categories  \\ 				///
	& (winsorized 5\%) & & future & & \\) 								///
	posthead(\hline )										///
	prefoot( ) postfoot(\hline \hline \end{tabular}) 
		
*-------------------------------------------------------------------------------
* 2.2.Lee bounds							
*-------------------------------------------------------------------------------
*2.2.1a - Calculates how many obs to be dropped -------------------------------
*----------------------------------------------
	set seed 12345

	*How many were assigned to treatment?
		count if accountAccess==1 & post == 0
		local treat_total = `r(N)'
	*How many were assigned to control?
		count if accountAccess==0 & post == 0
		local control_total = `r(N)'
	*What proportion of those assigned to treatment got it?
		count if accountAccess==1 & inSample==1 & post == 0
		local treat_incl = `r(N)'/`treat_total'
	*What proportion of those assigned to control got it?
		count if accountAccess==0 & inSample==1 & post == 0
		local control_incl = `r(N)'/`control_total'
	*Calculate trimming proportion
		local tp = abs(`treat_incl'-`control_incl') / ///
			(max(`treat_incl',`control_incl'))
	*How many to drop?
		count if accountAccess==0 & inSample==1 & post == 0
		local num_drop = floor(`tp'*`r(N)')	
		
	display as text "Treatment inclusion proportion ==`treat_incl'"
	display as text "Control inclusion proportion==`control_incl'"
	display as text "Trimming proportion==`tp'"
	display as text "Number of observations to be dropped==`num_drop'" /*42 */
	
	gen z = runiform() // we use random variable to break ties 
	
	// we have to drop 42 subjects from the control group to make it even

* 2.2.1b. Calculates table content --------------------------------------------

	local i = 1
	
	// iterate over outcomes over which to re-calculate with bands
	foreach y in w5_shortTermBorrowing stBorrowTotalIndex 			///
		anxietyFuture economicDifficulty {
		
		preserve
		reg d.`y' //trick to mark subjects nonmissing in both periods
		egen t1 = max(e(sample)), by(idBaseSurvey)
		
		//computes original coefficient from table 3	
		reghdfe `y' c.accountAccess#c.post post if t1 == 1, 		///	
		abs(idBaseSurvey) 						///
		vce(cluster groupId)
			
		if (abs(_b[c.accountAccess#c.post]) < 100) {
			local c`i'r1 = trim("`: display %12.3fc _b[c.accountAccess#c.post]'")
		} 
		else {
			local c`i'r1 = trim("`: display %12.0fc _b[c.accountAccess#c.post]'")
		}
		test c.accountAccess#c.post = 0
		// stores stars for coefficient
		if (`r(p)' <= 0.1 & `r(p)' > 0.05 ) { 
			local c`i'r1coef "*"
		}
		else if (`r(p)' <= 0.05 & `r(p)' > 0.01 ) { 
			local c`i'r1coef "**"
		}
		else if (`r(p)' <= 0.01 ) { 
			local c`i'r1coef "***"
		}
		else {
			local c`i'r1coef ""
		}
	
		//drops subjects not used in previous estimation (e.g. missings)
		keep if e(sample) == 1 
		
		//auxiliary steps that allow the dropping of the upper and lower	
		//part of control group's y 
		gsort -post +accountAccess +`y' +z
		gen id = _n if post == 1 & accountAccess == 0
		egen idpanel = max(id), by(idBaseSurvey)
		sum id
		gen sampleUB = (idpanel > `num_drop' | idpanel == .)
		gen sampleLB = (idpanel < (`r(max)' - `num_drop' + 1) | 	///
			idpanel == .)

		// lower bound: we drop the upper 42 subjects from y dist
		reghdfe `y' c.accountAccess#c.post post if t1 == 1 		///
			& sampleUB == 1, abs(idBaseSurvey) vce(cluster groupId) 
		if (abs(_b[c.accountAccess#c.post]) < 100) {
			local c`i'r2 = trim("`: display %12.3fc _b[c.accountAccess#c.post]'")
		} 
		else {
			local c`i'r2 = trim("`: display %12.0fc _b[c.accountAccess#c.post]'")
		}

							
		// upper bound: we drop the lower 42 subjects from y dist
		reghdfe `y' c.accountAccess#c.post post if t1 == 1 ///
			& sampleLB == 1, abs(idBaseSurvey) vce(cluster groupId) 
		
		if (abs(_b[c.accountAccess#c.post]) < 100) {
			local c`i'r3 = trim("`: display %12.3fc _b[c.accountAccess#c.post]'")
		} 
		else {
			local c`i'r3 = trim("`: display %12.0fc _b[c.accountAccess#c.post]'")
		}
		
        distinct idBaseSurvey  if e(sample) 
        estadd scalar num_ind = r(ndistinct)
        local c`i'r4 = trim("`: display %12.0fc e(num_ind)'")
		local c`i'r5 = trim("`: display %12.0fc e(N)'")
	
		restore	
		
		local i = `i' + 1
		
	}

* 2.2.2 Writes table --------------------------------------------------------

file open table using tab_leebound.tex, write text replace
	
	// writes table's header
	file write table "\begin{tabular}{l c c c c}" _n 							///
		"\hline \hline" _n 										///
		" & (1) & (2) & (3) & (4) \\" _n 								///
		" & Short-term & Short-term & Anxiety & Recent \\" _n 						///
		" & borrowing & borrowing & about & economic \\" _n 						///
		" & amount & categories & financial & difficulty \\" _n 					///
		" & & & future &  \\" _n 									///
		"\hline" _n
	
	file write table 												///
		"Point estimate & `c1r1'`c1r1coef' & `c2r1'`c2r1coef' & `c3r1'`c3r1coef' & `c4r1'`c4r1coef' \\" _n 	///
		"Lower bound & [`c1r2' & [`c2r2' & [`c3r2' & [`c4r2' \\" _n 						///
		"Upper bound & `c1r3'] & `c2r3'] & `c3r3'] & `c4r3'] \\" _n 						///
		"\hline" _n 												///
		"Individuals after trimming & `c1r4' & `c2r4' & `c3r4' & `c4r4' \\" _n 					///
		"Observations after trimming & `c1r5' & `c2r5' & `c3r5' & `c4r5' \\" _n 
	
		
	// writes table's closing argument
	file write table "\hline \hline" _n "\end{tabular}"
	
	file close table
		

***


*-------------------------------------------------------------------------------
* 2.3. Inverse Prob. Weighting								
*-------------------------------------------------------------------------------
* 2.3.1. Calculates table content --------------------------------------------
*-------------------------------------------------------------------------------
	
	eststo clear
	
	foreach y in w5_shortTermBorrowing stBorrowTotalIndex anxietyFuture 	///
		economicDifficulty { 
	
		reg d.`y' // Mark subjects nonmissing in both periods
		egen t1 = max(e(sample)), by(idBaseSurvey)

		reghdfe `y' c.accountAccess#c.post post if t1 == 1 [pw=ipw], 	///
		abs(idBaseSurvey) vce(cluster groupId) 
		
		distinct idBaseSurvey  if e(sample) 
		estadd scalar num_ind = r(ndistinct)
		estadd local ind_fixeff = "Yes"
		
		// adding control mean 
		sum `y' if accountAccess == 0 & post == 1
		if (abs(`r(mean)') < 100) {
			estadd local control_mean = trim("`: display %12.3fc r(mean)'")
		} 
		else {
			estadd local control_mean = trim("`: display %12.0fc r(mean)'")
		}

		drop t1
		eststo
	}
	

	reg d.numberConsumptionCutbacks
	
	egen t1 = max(e(sample)), by(idBaseSurvey)
	
	reghdfe numberConsumptionCutbacks c.accountAccess#c.post post if 	///
	t1 == 1 & economicShock2009 == 1 [pw=ipw], 				///
	abs(idBaseSurvey) vce(cluster groupId) 
	      
	distinct idBaseSurvey  if e(sample) 
	estadd scalar num_ind = r(ndistinct)
	estadd local ind_fixeff = "Yes"
	
	// adding control mean 
	sum numberConsumptionCutbacks if accountAccess == 0 & post == 1
	if (abs(`r(mean)') < 100) {
		estadd local control_mean = trim("`: display %12.3fc r(mean)'")
	} 
	else {
		estadd local control_mean = trim("`: display %12.0fc r(mean)'")
	}

	drop t1
	eststo
	
*-------------------------------------------------------------------------------	
* 2.3.2. Writes table --------------------------------------------------------	
*-------------------------------------------------------------------------------

	esttab est* using tab_ipw.tex, replace								///
	cells(b(star fmt(%12.3fc)) se(par fmt(%12.3fc))) label style(tex) nonumber			///
	stats( control_mean num_ind N ind_fixeff, fmt(%12.3fc %12.0fc %12.0fc)				///
	label("Control mean" "\hline Individuals" "Observations"					///
	"Individual FE")) mlabels(,none) 								///	
	collabels(, none) eqlabels(, none)  								///
	keep(c.accountAccess#c.post )									///
	varlabels(c.accountAccess#c.post "Account $\times$ post") 					///	
	starlevels(* 0.1 ** 0.05 *** 0.01) 								///
	prehead(\begin{tabular}{l*{@M}{c}} \hline \hline 						///
		& (1) & (2) & (3) & (4) & (5) \\ 							///
		& Total & Total & Anxiety & Recent & Consumption \\ 					///
		& short-term & short-term & about & economic & cutback \\ 				///
		& borrowing & borrowing & financial & difficulty & categories \\ 			///
		& amount & categories & future & & \\)  						///
	posthead(\hline ) 										///
	prefoot( ) postfoot(\hline \hline \end{tabular}) 
